package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String save(Video video) {
        video.setCreated(System.currentTimeMillis());
        video.setVid(idWorker.getNextId("video"));
        mongoTemplate.save(video); //mongodb中保存完成之后，自动生成id。
        return video.getId().toHexString();
    }

    //分页查询所有视频数据
    public List<Video> findAll(int page, int pagesize) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Video.class);
    }

    //根据PID查询数据
    public List<Video> findByVids(List<Long> vids) {
        Criteria criteria = Criteria.where("vid").in(vids);
        return mongoTemplate.find(Query.query(criteria),Video.class);
    }

    //根据用户id，分页查询用户发布的视频列表
    public PageResult findByUserId(Long userId, int page, int pagesize) {
        //1、构建查询条件
        Query query = Query.query(Criteria.where("userId").is(userId));
        //2、查询总数据
        long count = mongoTemplate.count(query, Video.class);
        //3、分页查询数据列表
        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Video> list = mongoTemplate.find(query, Video.class);
        //4、构造返回
        return new PageResult(page,pagesize,count,list);
    }
}
